import { defineStore } from 'pinia'
import { ref } from 'vue'
import {
    getOrders,
    getOrderDetail,
    createOrder,
    cancelOrder,
    getOrdersByUser,
    getOrdersByStatus
} from '@/api/order'

export const useOrderStore = defineStore('order', () => {
    const orders = ref([])
    const currentOrder = ref(null)
    const loading = ref(false)
    const pagination = ref({
        page: 1,
        pageSize: 10,
        total: 0
    })

    const fetchOrders = async (params = {}) => {
        loading.value = true
        try {
            const response = await getOrders({
                ...params,
                page: pagination.value.page,
                pageSize: pagination.value.pageSize,

            })
            orders.value = response.data.records
            pagination.value.total = response.data.total
        } finally {
            loading.value = false
        }
    }

    const fetchOrderDetail = async (id) => {
        loading.value = true
        try {
            const response = await getOrderDetail(id)
            currentOrder.value = response.data
        } finally {
            loading.value = false
        }
    }

    const addOrder = async (orderData) => {
        loading.value = true
        try {
            await createOrder(orderData)
            await fetchOrders()
        } finally {
            loading.value = false
        }
    }

    const cancel = async (id) => {
        loading.value = true
        try {
            await cancelOrder(id)
            await fetchOrders()
        } finally {
            loading.value = false
        }
    }

    const fetchUserOrders = async (userId) => {
        loading.value = true
        try {
            const response = await getOrdersByUser(userId)
            orders.value = response.data
        } finally {
            loading.value = false
        }
    }

    const fetchOrdersByStatus = async (status) => {
        loading.value = true
        try {
            const response = await getOrdersByStatus(status)
            orders.value = response.data
        } finally {
            loading.value = false
        }
    }

    return {
        orders,
        currentOrder,
        loading,
        pagination,
        fetchOrders,
        fetchOrderDetail,
        addOrder,
        cancel,
        fetchUserOrders,
        fetchOrdersByStatus
    }
})